@extends('layouts.app')

@section('title', '账单明细')

@section('main-content')
<div class="app-container">
    <div class="header" style="position: relative;">
        <div class="greeting">账单明细</div>
        <div class="date month-selector" id="current-month">
            <span id="current-month-text">{{ date('Y年n月') }}</span>
            <span class="month-arrow">▼</span>
        </div>

        <!-- 日历按钮 -->
        <button class="calendar-btn" id="calendar-btn">
            <span>📅</span>
            <span>日历</span>
        </button>

        <!-- 月份选择器 -->
        <div class="month-picker" id="month-picker" style="display: none;">
            <div class="month-picker-header">
                <button class="year-btn" id="prev-year">‹</button>
                <span class="year-display" id="year-display">{{ date('Y') }}</span>
                <button class="year-btn" id="next-year">›</button>
            </div>
            <div class="month-grid">
                @for($i = 1; $i <= 12; $i++)
                <div class="month-item" data-month="{{ $i }}">
                    <div class="month-name">{{ $i }}月</div>
                    <div class="month-summary" id="month-summary-{{ $i }}">
                        <div class="month-balance">¥0</div>
                        <div class="month-details">
                            <span class="month-expense">支出: ¥0</span>
                            <span class="month-income">收入: ¥0</span>
                        </div>
                    </div>
                </div>
                @endfor
            </div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div style="padding: 15px 20px; display: flex; justify-content: space-between; align-items: center;">
        <div style="display: flex; gap: 10px;">
            <div class="filter-btn active" data-filter="all">全部</div>
            <div class="filter-btn" data-filter="expense">支出</div>
            <div class="filter-btn" data-filter="income">收入</div>
        </div>
        <div class="advanced-filter-btn" id="advanced-filter-btn" style="display: flex; align-items: center; gap: 5px; color: #667eea; font-size: 14px; cursor: pointer;">
            <span>筛选</span>
            <span style="font-size: 16px;">🔍</span>
        </div>
    </div>

    <!-- 高级筛选面板 -->
    <div class="advanced-filter-panel" id="advanced-filter-panel" style="display: none; padding: 15px 20px; background: #f8f9fa; border-radius: 12px; margin: 0 10px 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
        <div style="margin-bottom: 15px;">
            <div class="form-label">时间区间</div>
            <div style="display: flex; gap: 10px; align-items: center;">
                <input type="date" class="form-input" id="date-from" style="flex: 1;">
                <span>至</span>
                <input type="date" class="form-input" id="date-to" style="flex: 1;">
            </div>
        </div>

        <div style="margin-bottom: 15px;">
            <div class="form-label">模糊搜索</div>
            <input type="text" class="form-input" id="search-input" placeholder="搜索描述内容..." style="width: 100%;">
        </div>

        <div style="margin-bottom: 15px;">
            <div class="form-label">用户筛选</div>
            <div style="display: flex; gap: 8px; flex-wrap: wrap;" id="user-filter-container">
                <div class="user-filter-btn active" data-user="all" style="padding: 6px 12px; border-radius: 16px; background: #667eea; color: white; font-size: 12px; cursor: pointer; border: 1px solid #667eea;">全部用户</div>
            </div>
        </div>

        <div id="category-filter-container" style="margin-bottom: 15px; ">
            <div class="form-label">分类筛选</div>

            <!-- 类型切换按钮 -->
            <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                <button class="btn btn-secondary" id="filter-income-btn" style="flex: 1; padding: 8px; font-size: 14px;">支出</button>
                <button class="btn btn-secondary" id="filter-expense-btn" style="flex: 1; padding: 8px; font-size: 14px;">收入</button>
            </div>

            <!-- 支出分类 -->
            <div class="category-selector" id="filter-expense-categories" style="display: none;">
                <!-- 动态生成支出分类按钮 -->
            </div>

            <!-- 收入分类 -->
            <div class="category-selector" id="filter-income-categories" style="display: none;">
                <!-- 动态生成收入分类按钮 -->
            </div>

            <!-- 支出二级分类容器 -->
            <div id="filter-expense-subcategories-container">
                <!-- 动态生成支出二级分类 -->
            </div>

            <!-- 收入二级分类容器 -->
            <div id="filter-income-subcategories-container">
                <!-- 动态生成收入二级分类 -->
            </div>

            <div class="category-selected-info" id="filter-category-selected-info" style="display: none;"></div>
        </div>

        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" id="apply-filter-btn" style="flex: 1;">应用筛选</button>
            <button class="btn btn-secondary" id="reset-filter-btn" style="flex: 1;">重置</button>
        </div>
    </div>

    <!-- 明细列表 -->
    <div class="detail-list" id="detail-list">
        <!-- 动态加载内容 -->
        <div class="loading" id="loading" style="text-align: center; padding: 40px; color: #999;">
            <div>加载中...</div>
        </div>
    </div>

    <!-- 回到顶部按钮 -->
    <div class="back-to-top" id="back-to-top" style="display: none;">
        <span>↑</span>
    </div>

    <!-- 编辑交易记录模态框 -->
    <div class="modal" id="edit-transaction-modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>编辑记账记录</h3>
                <button class="modal-close" id="edit-modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <form id="edit-transaction-form">
                    <input type="hidden" id="edit-transaction-id">

                    <!-- 类型选择 -->
                    <div class="form-group">
                        <label class="form-label">类型</label>
                        <div class="type-selector">
                            <div class="type-btn" data-type="expense" id="edit-expense-btn">
                                <span class="type-icon">💸</span>
                                <span>支出</span>
                            </div>
                            <div class="type-btn" data-type="income" id="edit-income-btn">
                                <span class="type-icon">💰</span>
                                <span>收入</span>
                            </div>
                        </div>
                    </div>

                    <!-- 金额输入 -->
                    <div class="form-group">
                        <label class="form-label">金额</label>
                        <input type="number" class="form-input" id="edit-amount" step="0.01" min="0.01" placeholder="请输入金额" required>
                    </div>

                    <!-- 分类选择 -->
                    <div class="form-group">
                        <label class="form-label">分类</label>
                        <div class="category-selector" id="edit-categories">
                            <!-- 动态生成分类按钮 -->
                        </div>
                    </div>

                    <!-- 二级分类选择 -->
                    <div class="form-group" id="edit-subcategory-group" style="display: none;">
                        <label class="form-label">二级分类</label>
                        <div class="subcategory-selector" id="edit-subcategories">
                            <!-- 动态生成二级分类按钮 -->
                        </div>
                    </div>

                    <!-- 日期选择 -->
                    <div class="form-group">
                        <label class="form-label">日期</label>
                        <input type="date" class="form-input" id="edit-date" required>
                    </div>

                    <!-- 备注输入 -->
                    <div class="form-group">
                        <label class="form-label">备注</label>
                        <input type="text" class="form-input" id="edit-description" placeholder="请输入备注（可选）" maxlength="255">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="edit-cancel-btn">取消</button>
                <button class="btn btn-primary" id="edit-save-btn">保存</button>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal" id="delete-transaction-modal" style="display: none;">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="modal-close" id="delete-modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <p style="text-align: center; margin: 20px 0;">确定要删除这条记账记录吗？</p>
                <p style="text-align: center; color: #999; font-size: 14px;">此操作不可撤销</p>
                <input type="hidden" id="delete-transaction-id">
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="delete-cancel-btn">取消</button>
                <button class="btn btn-danger" id="delete-confirm-btn">删除</button>
            </div>
        </div>
    </div>

    <!-- 日历视图模态框 -->
    <div class="calendar-view" id="calendar-view" style="display: none;">
        <div class="calendar-container">
            <div class="calendar-header">
                <div class="calendar-title">日历统计</div>
                <button class="calendar-close" id="calendar-close">&times;</button>
            </div>
            <div class="calendar-nav">
                <button class="calendar-nav-btn" id="calendar-prev-month">‹</button>
                <div class="calendar-month-year" id="calendar-month-year">{{ date('Y年n月') }}</div>
                <button class="calendar-nav-btn" id="calendar-next-month">›</button>
            </div>
            <div class="calendar-grid">
                <div class="calendar-weekday">日</div>
                <div class="calendar-weekday">一</div>
                <div class="calendar-weekday">二</div>
                <div class="calendar-weekday">三</div>
                <div class="calendar-weekday">四</div>
                <div class="calendar-weekday">五</div>
                <div class="calendar-weekday">六</div>
                <div class="calendar-days" id="calendar-days">
                    <!-- 动态生成日期 -->
                </div>
            </div>
            <div class="calendar-legend">
                <div class="calendar-legend-item">
                    <div class="calendar-legend-dot legend-expense"></div>
                    <span>支出</span>
                </div>
                <div class="calendar-legend-item">
                    <div class="calendar-legend-dot legend-income"></div>
                    <span>收入</span>
                </div>
                <div class="calendar-legend-item">
                    <div class="calendar-legend-dot legend-today"></div>
                    <span>今天</span>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
    <style>
        .transaction-desc {
            font-size: 12px;
            color: #718096;
            margin: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 二级分类样式 */
        .subcategory-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }

        .subcategory-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
        }

        .subcategory-item.active .subcategory-icon {
            background: #667eea;
            color: white;
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
        }

        .subcategory-name {
            font-size: 12px;
            color: #718096;
        }

        .subcategory-item.active .subcategory-name {
            color: #667eea;
            font-weight: 600;
        }

        /* 筛选器中的分类样式调整 */
        .filter-category-selector .category-item {
            padding: 8px;
        }

        .filter-category-selector .category-icon {
            width: 40px;
            height: 40px;
            font-size: 16px;
        }

        .filter-subcategory-selector {
            background: #f0f5ff;
            border-radius: 12px;
            padding: 15px;
            margin-top: 10px;
        }

        /* 月份选择器样式 */
        .month-selector {
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s ease;
        }

        .month-selector:hover {
            color: #667eea;
        }

        .month-arrow {
            font-size: 12px;
            transition: transform 0.3s ease;
        }

        .month-selector.active .month-arrow {
            transform: rotate(180deg);
        }

        .month-picker {
            position: absolute;
            top: 100%;
            left: 20px;
            right: 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            z-index: 9999;
            padding: 20px;
            margin-top: 10px;
        }

        .month-picker-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .year-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: #667eea;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .year-btn:hover {
            background: #f0f5ff;
        }

        .year-display {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }

        .month-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
        }

        .month-item {
            padding: 12px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #4a5568;
            border: 1px solid #e2e8f0;
        }

        .month-item:hover {
            background: #f0f5ff;
            color: #667eea;
            border-color: #667eea;
        }

        .month-item.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .month-name {
            font-weight: 600;
            margin-bottom: 8px;
        }

        .month-summary {
            font-size: 11px;
            line-height: 1.3;
        }

        .month-balance {
            font-weight: 600;
            margin-bottom: 4px;
            color: #d69e2e;
        }

        .month-item.active .month-balance {
            color: #ffd700;
        }

        .month-details {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .month-expense {
            color: #e53e3e;
        }

        .month-income {
            color: #38a169;
        }

        .month-item.active .month-expense,
        .month-item.active .month-income {
            color: rgba(255, 255, 255, 0.9);
        }

        /* 紧凑交易项样式 */
        .transaction-item {
            padding: 8px 15px !important;
            margin-bottom: 0 !important;
            min-height: auto !important;
            display: flex !important;
            align-items: center !important;
            background: none !important;
            border: none !important;
            box-shadow: none !important;
            border-radius: 0 !important;
            gap: 0 !important;
            border-bottom: 1px solid #f0f0f0 !important;
        }

        .transaction-left {
            display: flex !important;
            align-items: center !important;
            flex: 1 !important;
        }

        .transaction-info {
            margin-left: 0px !important;
            flex: 1 !important;
            min-width: 0;
        }

        .transaction-info h4 {
            font-size: 13px !important;
            line-height: 1.2 !important;
            margin: 0 !important;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

        .transaction-info h4:hover {
            background-color: #f8f9fa;
        }

        .transaction-icon {
            width: 28px !important;
            height: 28px !important;
            font-size: 14px !important;
            flex-shrink: 0 !important;
        }

        .transaction-amount {
            font-size: 14px !important;
            font-weight: 600 !important;
            margin-right: 0px !important;
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

        .transaction-amount:hover {
            background-color: #f8f9fa;
        }

        /* 选项按钮 */
        .transaction-options {
            width: 24px !important;
            height: 24px !important;
            border-radius: 50% !important;
            background: #f8f9fa !important;
            border: none !important;
            cursor: pointer !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-size: 12px !important;
            color: #666 !important;
            flex-shrink: 0 !important;
        }

        .transaction-options:hover {
            background: #e9ecef !important;
        }

        /* 精简日期头部为一行 */
        .detail-date-header {
            padding: 8px 15px !important;
            margin: 0 !important;
            font-size: 13px !important;
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            background: #f8f9fa !important;
            border-radius: 0 !important;
            border-bottom: 2px solid #e9ecef !important;
        }

        .detail-date-header .date-info {
            display: flex !important;
            align-items: center !important;
            gap: 8px !important;
        }

        .detail-date-header .weekday {
            font-size: 11px !important;
            color: #666 !important;
        }

        .detail-date-summary {
            font-size: 11px !important;
            display: flex !important;
            gap: 8px !important;
        }

        .detail-date-summary span:first-child {
            color: #dc3545 !important; /* 支出红色 */
        }

        .detail-date-summary span:last-child {
            color: #28a745 !important; /* 收入绿色 */
        }

        /* 日期分组间距 */
        .date-group {
            margin-bottom: 12px !important;
        }

        .date-group:last-child {
            margin-bottom: 0 !important;
        }

        .detail-list {
            padding-bottom: 200px !important;
        }

        /* 用户头像样式（家庭账本） */
        .item-user-avatar {
            width: 28px !important;
            height: 28px !important;
            border-radius: 50% !important;
            margin-right: 0px !important;
            flex-shrink: 0 !important;
            background: #007bff !important;
            color: white !important;
            font-size: 11px !important;
            display: flex !important;
            align-items: center!important;
            justify-content: center!important;
            text-transform: uppercase!important;
        }

        .filter-btn {
            padding: 6px 12px;
            border-radius: 16px;
            background: #f8f9fa;
            color: #495057;
            font-size: 12px;
            cursor: pointer;
            border: 1px solid #dee2e6;
            transition: all 0.3s ease;
        }

        .filter-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .user-filter-btn {
            padding: 6px 12px;
            border-radius: 16px;
            background: #f8f9fa;
            color: #495057;
            font-size: 12px;
            cursor: pointer;
            border: 1px solid #dee2e6;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            white-space: nowrap;
        }

        .user-filter-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .user-filter-btn img {
            flex-shrink: 0;
        }

        .form-label {
            font-size: 14px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
        }

        .form-input {
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            background: white;
        }

        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a67d8;
        }

        .btn-secondary {
            background: #e2e8f0;
            color: #4a5568;
        }

        .btn-secondary:hover {
            background: #cbd5e0;
        }

        .category-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            padding: 10px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .category-item.active {
            background: #f0f5ff;
        }

        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
        }

        .category-item.active .category-icon {
            background: #667eea;
            color: white;
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
        }

        .category-name {
            font-size: 12px;
            color: #718096;
            text-align: center;
        }

        .category-item.active .category-name {
            color: #667eea;
            font-weight: 600;
        }

        .no-data {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        .no-data-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .no-data-text {
            font-size: 16px;
            margin-bottom: 8px;
        }

        .no-data-desc {
            font-size: 14px;
            color: #ccc;
        }

        /* 日历按钮样式 */
        .calendar-btn {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .calendar-btn:hover {
            background: #5a67d8;
            transform: translateY(-50%) scale(1.05);
        }

        /* 日历视图样式 */
        .calendar-view {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 10000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .calendar-container {
            background: white;
            border-radius: 16px;
            padding: 20px;
            max-width: 400px;
            width: 100%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e2e8f0;
        }

        .calendar-title {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }

        .calendar-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #718096;
            cursor: pointer;
            padding: 5px;
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        .calendar-close:hover {
            background: #f7fafc;
            color: #2d3748;
        }

        .calendar-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .calendar-nav-btn {
            background: none;
            border: none;
            font-size: 18px;
            color: #667eea;
            cursor: pointer;
            padding: 8px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .calendar-nav-btn:hover {
            background: #f0f5ff;
        }

        .calendar-month-year {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 2px;
            margin-bottom: 10px;
            width: 100%;
            max-width: 100%;
        }

        .calendar-weekday {
            text-align: center;
            padding: 8px 4px;
            font-size: 12px;
            color: #718096;
            font-weight: 600;
        }

        .calendar-day {
            aspect-ratio: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
            position: relative;
            padding: 4px 2px;
            font-size: 12px;
        }

        .calendar-day:hover {
            background: #f0f5ff;
        }

        .calendar-day.today {
            border: 2px solid #667eea !important;
            /*background: #667eea;*/
            /*color: white;*/
        }

        .calendar-day.has-data {
            background: #e6fffa;
            border: 1px solid #38b2ac;
        }

        .calendar-day.has-data:hover {
            background: #b2f5ea;
        }

        .calendar-day.other-month {
            color: #cbd5e0;
        }

        .calendar-day-number {
            font-weight: 600;
            margin-bottom: 2px;
        }

        .calendar-day-balance {
            font-size: 9px;
            line-height: 1;
            color: #d69e2e;
            font-weight: bold;
            margin-bottom: 1px;
        }

        .calendar-day-amounts {
            display: flex;
            justify-content: space-between;
            font-size: 7px;
            line-height: 1;
        }

        .calendar-day-expense {
            color: #e53e3e;
        }

        .calendar-day-income {
            color: #38a169;
        }

        .calendar-day-single {
            font-weight: bold;
            font-size: 10px;
            line-height: 1.2;
            text-align: center;
        }

        .calendar-day.positive-balance {
            border: 2px solid #38a169;
        }

        .calendar-day.negative-balance {
            border: 2px solid #fba3a3
        }

        .calendar-legend {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e2e8f0;
            font-size: 12px;
        }

        .calendar-legend-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .calendar-legend-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .legend-expense {
            background: #fba3a3;
        }

        .legend-income {
            background: #38a169;
        }

        /* 回到顶部按钮样式 */
        .back-to-top {
            position: fixed;
            bottom: 100px;
            right: 30px;
            width: 30px;
            height: 30px;
            background: #667eea;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .back-to-top:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }

        .back-to-top span {
            color: white;
            font-size: 20px;
            font-weight: bold;
        }
        .legend-today {
            background: #667eea;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .type-selector {
            display: flex;
            gap: 10px;
        }

        .type-btn {
            flex: 1;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
        }

        .type-btn:hover {
            border-color: #667eea;
            background: #f0f5ff;
        }

        .type-btn.active {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }

        .type-icon {
            font-size: 20px;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        /* 编辑表单中的分类选择器 */
        #edit-categories .category-item,
        #edit-subcategories .subcategory-item {
            padding: 8px;
        }

        #edit-categories .category-icon,
        #edit-subcategories .subcategory-icon {
            width: 36px;
            height: 36px;
            font-size: 14px;
        }

        #edit-categories .category-name,
        #edit-subcategories .subcategory-name {
            font-size: 11px;
        }

        /* 操作按钮悬停效果 */
        .transaction-options-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            min-width: 100px;
            overflow: hidden;
            display: none;
        }

        .transaction-options-menu.show {
            display: block;
        }

        .transaction-options-menu-item {
            padding: 10px 15px;
            cursor: pointer;
            font-size: 14px;
            color: #4a5568;
            transition: background-color 0.2s;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
        }

        .transaction-options-menu-item:hover {
            background: #f8f9fa;
        }

        .transaction-options-menu-item.delete {
            color: #dc3545;
        }

        .transaction-options-menu-item.delete:hover {
            background: #fff5f5;
        }

        .transaction-item {
            /*position: relative;*/
        }

        .transaction-options {
            position: relative;
            display: flex;
            align-items: center;
        }

        .transaction-options-btn {
            background: none;
            border: none;
            color: #999;
            font-size: 16px;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: all 0.3s ease;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .transaction-options-btn:hover {
            background: #f8f9fa;
            color: #666;
        }

        .calendar-days {
            display: contents;
        }
    </style>
@endpush
@push('scripts')
<script>
$(document).ready(function() {
    let currentYear = {{ date('Y') }};
    let currentMonth = {{ date('n') }};
    let currentFilter = 'all';
    let filterOptions = {};
    let advancedFilters = {
        dateFrom: '',
        dateTo: '',
        search: '',
        userId: 'all',
        categoryId: '',
        subCategoryId: ''
    };

    // 初始化
    init();

    function init() {
        loadFilterOptions();
        loadData();
        loadMonthSummary();
        bindEvents();
    }

    // 绑定事件
    function bindEvents() {
        // 月份选择器
        $('#current-month').click(function() {
            $('#month-picker').toggle();
            $(this).toggleClass('active');
        });

        // 年份切换
        $('#prev-year').click(function() {
            currentYear--;
            $('#year-display').text(currentYear);
            loadMonthSummary();
            calendarCurrentMonth = currentMonth;
        });

        $('#next-year').click(function() {
            currentYear++;
            $('#year-display').text(currentYear);
            loadMonthSummary();
            calendarCurrentMonth = currentMonth;
        });

        // 月份选择
        $('.month-item').click(function() {
            currentMonth = parseInt($(this).data('month'));
            $('.month-item').removeClass('active');
            $(this).addClass('active');
            $('#current-month-text').text(currentYear + '年' + currentMonth + '月');
            $('#month-picker').hide();
            $('#current-month').removeClass('active');
            loadData();
            loadMonthSummary(); // 加载月份累计情况
            calendarCurrentYear = currentYear;
        });

        // 回到顶部按钮功能
        $('#back-to-top').click(function() {
            $('html, body').animate({
                scrollTop: 0
            }, 500);
        });

        // 监听滚动事件，控制回到顶部按钮显示
        $(window).scroll(function() {
            if ($(this).scrollTop() > 300) {
                $('#back-to-top').fadeIn();
            } else {
                $('#back-to-top').fadeOut();
            }
        });

        // 类型筛选
        $('.filter-btn').click(function() {
            currentFilter = $(this).data('filter');
            $('.filter-btn').removeClass('active');
            $(this).addClass('active');
            loadData();
        });

        // 高级筛选
        $('#advanced-filter-btn').click(function() {
            $('#advanced-filter-panel').toggle();
        });

        // 应用筛选
        $('#apply-filter-btn').click(function() {
            advancedFilters.dateFrom = $('#date-from').val();
            advancedFilters.dateTo = $('#date-to').val();
            advancedFilters.search = $('#search-input').val();
            advancedFilters.userId = $('.user-filter-btn.active').data('user');
            advancedFilters.categoryId = $('.category-item.active').data('category-id') || '';
            advancedFilters.subCategoryId = $('.subcategory-item.active').data('subcategory-id') || '';

            loadData();
            $('#advanced-filter-panel').hide();
        });

        // 重置筛选
        $('#reset-filter-btn').click(function() {
            advancedFilters = {
                dateFrom: '',
                dateTo: '',
                search: '',
                userId: 'all',
                categoryId: '',
                subCategoryId: ''
            };

            $('#date-from').val('');
            $('#date-to').val('');
            $('#search-input').val('');
            $('.user-filter-btn').removeClass('active');
            $('.user-filter-btn[data-user="all"]').addClass('active');
            $('.category-item').removeClass('active');
            $('.subcategory-item').removeClass('active');
            $('.subcategory-selector').hide();
            $('#filter-category-selected-info').hide();

            loadData();
            $('#advanced-filter-panel').hide();
        });

        // 点击外部关闭月份选择器
        $(document).click(function(e) {
            if (!$(e.target).closest('#current-month, #month-picker').length) {
                $('#month-picker').hide();
                $('#current-month').removeClass('active');
            }
        });
    }

    // 加载筛选选项
    function loadFilterOptions() {
        $.get('{{ route("details.filter-options") }}', function(data) {
            filterOptions = data;

            // 渲染用户筛选
            renderUserFilter(data.users);

            // 渲染分类筛选
            renderCategoryFilter(data.categories);

            // 初始化分类类型切换
            initCategoryTypeSwitch();
        }).fail(function() {
            console.error('加载筛选选项失败');
        });
    }

    // 渲染用户筛选
    function renderUserFilter(users) {
        let html = '<div class="user-filter-btn active" data-user="all">全部用户</div>';
        users.forEach(function(user) {
            // 获取用户头像或昵称首字
            let userDisplay = '';
            if (user.avatar_url) {
                userDisplay = `<img src="${user.avatar_url}" alt="${user.nickname || user.name}" style="width: 20px; height: 20px; border-radius: 50%; margin-right: 6px; object-fit: cover;">`;
            } else {
                // 使用昵称首字或用户名首字
                const displayName = user.nickname || user.name;
                const firstChar = displayName.charAt(0).toUpperCase();
                userDisplay = `<div style="width: 20px; height: 20px; border-radius: 50%; background: #667eea; color: white; font-size: 10px; display: inline-flex; align-items: center; justify-content: center; margin-right: 6px;">${firstChar}</div>`;
            }

            // 使用昵称优先，如果没有昵称则使用用户名
            const userName = user.nickname || user.name;
            html += `<div class="user-filter-btn" data-user="${user.id}" style="display: flex; align-items: center;">${userDisplay}${userName}</div>`;
        });
        $('#user-filter-container').html(html);

        // 绑定用户筛选事件
        $('.user-filter-btn').click(function() {
            $('.user-filter-btn').removeClass('active');
            $(this).addClass('active');
        });
    }

    // 初始化分类筛选类型切换
    function initCategoryTypeSwitch() {
        // 默认显示支出分类
        // $('#filter-expense-btn').addClass('btn-primary').removeClass('btn-secondary');
        // $('#filter-expense-categories').show();
        // $('#filter-expense-subcategories-container').show();
        // $('#filter-income-categories').hide();
        // $('#filter-income-subcategories-container').hide();

        // 支出按钮点击事件
        $('#filter-expense-btn').click(function() {
            if (!$(this).hasClass('btn-primary')) {
                // 切换按钮样式
                $('#filter-expense-btn').addClass('btn-primary').removeClass('btn-secondary');
                $('#filter-income-btn').addClass('btn-secondary').removeClass('btn-primary');

                // 显示支出分类，隐藏收入分类
                $('#filter-expense-categories').show();
                $('#filter-expense-subcategories-container').show();
                $('#filter-income-categories').hide();
                $('#filter-income-subcategories-container').hide();

                // 清除收入分类的选中状态
                $('#filter-income-categories .category-item').removeClass('active');
                $('#filter-income-subcategories-container .subcategory-item').removeClass('active');
                $('.subcategory-selector').hide();

                // 更新选中信息
                updateFilterCategoryInfo();
            }
        });

        // 收入按钮点击事件
        $('#filter-income-btn').click(function() {
            if (!$(this).hasClass('btn-primary')) {
                // 切换按钮样式
                $('#filter-income-btn').addClass('btn-primary').removeClass('btn-secondary');
                $('#filter-expense-btn').addClass('btn-secondary').removeClass('btn-primary');

                // 显示收入分类，隐藏支出分类
                $('#filter-income-categories').show();
                $('#filter-income-subcategories-container').show();
                $('#filter-expense-categories').hide();
                $('#filter-expense-subcategories-container').hide();

                // 清除支出分类的选中状态
                $('#filter-expense-categories .category-item').removeClass('active');
                $('#filter-expense-subcategories-container .subcategory-item').removeClass('active');
                $('.subcategory-selector').hide();

                // 更新选中信息
                updateFilterCategoryInfo();
            }
        });
    }

    // 渲染分类筛选
    function renderCategoryFilter(categories) {
        // 分离支出和收入分类
        const expenseCategories = categories.filter(cat => cat.type === 1); // 支出
        const incomeCategories = categories.filter(cat => cat.type === 2);  // 收入

        // 渲染支出分类
        let expenseHtml = '';
        if (expenseCategories.length > 0) {
            expenseCategories.forEach(function(cat) {
                expenseHtml += `
                    <div class="category-item" data-category="${cat.name}" data-category-id="${cat.id}" data-type="expense">
                        <div class="category-icon">${cat.icon}</div>
                        <div class="category-name">${cat.name}</div>
                    </div>
                `;
            });
        } else {
            expenseHtml = '<div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无支出分类</div>';
        }
        $('#filter-expense-categories').html(expenseHtml);

        // 渲染收入分类
        let incomeHtml = '';
        if (incomeCategories.length > 0) {
            incomeCategories.forEach(function(cat) {
                incomeHtml += `
                    <div class="category-item" data-category="${cat.name}" data-category-id="${cat.id}" data-type="income">
                        <div class="category-icon">${cat.icon}</div>
                        <div class="category-name">${cat.name}</div>
                    </div>
                `;
            });
        } else {
            incomeHtml = '<div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无收入分类</div>';
        }
        $('#filter-income-categories').html(incomeHtml);

        // 渲染支出二级分类
        let expenseSubHtml = '';
        expenseCategories.forEach(function(cat) {
            if (cat.subcategories && cat.subcategories.length > 0) {
                expenseSubHtml += `
                    <div class="subcategory-selector" id="filter-subcategory-expense-${cat.id}" style="display: none;">
                        <div class="subcategory-title">${cat.name} - 二级分类</div>
                        <div class="subcategory-box">
                `;
                cat.subcategories.forEach(function(subCat) {
                    expenseSubHtml += `
                        <div class="subcategory-item" data-subcategory="${subCat.name}" data-subcategory-id="${subCat.id}">
                            <div class="subcategory-icon">${subCat.icon}</div>
                            <div class="subcategory-name">${subCat.name}</div>
                        </div>
                    `;
                });
                expenseSubHtml += `
                        </div>
                    </div>
                `;
            }
        });
        $('#filter-expense-subcategories-container').html(expenseSubHtml);

        // 渲染收入二级分类
        let incomeSubHtml = '';
        incomeCategories.forEach(function(cat) {
            if (cat.subcategories && cat.subcategories.length > 0) {
                incomeSubHtml += `
                    <div class="subcategory-selector" id="filter-subcategory-income-${cat.id}" style="display: none;">
                        <div class="subcategory-title">${cat.name} - 二级分类</div>
                        <div class="subcategory-box">
                `;
                cat.subcategories.forEach(function(subCat) {
                    incomeSubHtml += `
                        <div class="subcategory-item" data-subcategory="${subCat.name}" data-subcategory-id="${subCat.id}">
                            <div class="subcategory-icon">${subCat.icon}</div>
                            <div class="subcategory-name">${subCat.name}</div>
                        </div>
                    `;
                });
                incomeSubHtml += `
                        </div>
                    </div>
                `;
            }
        });
        $('#filter-income-subcategories-container').html(incomeSubHtml);

        // 绑定分类选择事件
        $('.category-item').click(function() {
            const categoryId = $(this).data('category-id');
            const categoryType = $(this).data('type');

            // 清除所有分类的选中状态
            $('.category-item').removeClass('active');
            $(this).addClass('active');

            // 隐藏所有二级分类
            $('.subcategory-selector').hide();
            $('.subcategory-item').removeClass('active');

            // 显示对应的二级分类
            const subcategorySelector = $(`#filter-subcategory-${categoryType}-${categoryId}`);
            if (subcategorySelector.length > 0) {
                subcategorySelector.show();
            }

            // 更新选中信息
            updateFilterCategoryInfo();
        });

        // 绑定二级分类选择事件
        $('.subcategory-item').click(function() {
            const parent = $(this).closest('.subcategory-selector');
            parent.find('.subcategory-item').removeClass('active');
            $(this).addClass('active');

            // 更新选中信息
            updateFilterCategoryInfo();
        });
    }

    // 更新筛选分类选中信息
    function updateFilterCategoryInfo() {
        const categoryName = $('.category-item.active').data('category');
        const subcategoryName = $('.subcategory-item.active').data('subcategory');

        if (categoryName && subcategoryName) {
            $('#filter-category-selected-info').text(`已选: ${categoryName} - ${subcategoryName}`).show();
        } else if (categoryName) {
            $('#filter-category-selected-info').text(`已选: ${categoryName}`).show();
        } else {
            $('#filter-category-selected-info').hide();
        }
    }

    // 加载数据
    function loadData() {
        $('#loading').show();

        let params = {
            year: currentYear,
            month: currentMonth,
            type: currentFilter
        };

        // 添加高级筛选参数
        if (advancedFilters.dateFrom) params.date_from = advancedFilters.dateFrom;
        if (advancedFilters.dateTo) params.date_to = advancedFilters.dateTo;
        if (advancedFilters.search) params.search = advancedFilters.search;
        if (advancedFilters.userId !== 'all') params.user_id = advancedFilters.userId;
        if (advancedFilters.categoryId) params.category_id = advancedFilters.categoryId;
        if (advancedFilters.subCategoryId) params.subcategory_id = advancedFilters.subCategoryId;

        $.get('{{ route("details.data") }}', params, function(data) {
            renderTransactions(data);
            $('#loading').hide();
        }).fail(function() {
            $('#loading').hide();
            $('#detail-list').html('<div class="no-data"><div class="no-data-icon">😔</div><div class="no-data-text">加载失败</div><div class="no-data-desc">请检查网络连接后重试</div></div>');
        });
    }

    // 加载月份累计情况
    function loadMonthSummary() {
        // 使用月度对比接口获取当前年份的12个月数据
        $.ajax({
            url: '{{ route("statistics.comparison") }}',
            method: 'GET',
            data: {
                year: currentYear
            },
            success: function(response) {
                if (response.success && response.data) {
                    const data = response.data;

                    // 重置所有月份显示
                    for (let i = 1; i <= 12; i++) {
                        updateMonthDisplay(i, 0, 0, 0);
                    }

                    // 更新有数据的月份
                    data.forEach(function(monthData) {
                        // 从 "2024-01" 格式中提取月份
                        const monthParts = monthData.month.split('-');
                        const year = parseInt(monthParts[0]);
                        const month = parseInt(monthParts[1]);

                        // 只显示当前年份的数据
                        if (year === currentYear) {
                            const expense = parseFloat(monthData.expense) || 0;
                            const income = parseFloat(monthData.income) || 0;
                            const balance = parseFloat(monthData.net) || 0;

                            updateMonthDisplay(month, expense, income, balance);
                        }
                    });
                }
            },
            error: function() {
                console.error('加载月份累计数据失败');
            }
        });
    }

    // 更新月份显示
    function updateMonthDisplay(month, expense, income, balance) {
        const summaryElement = $(`#month-summary-${month}`);
        const balanceText = balance >= 0 ? `+¥${formatMonthNumber(balance)}` : `-¥${formatMonthNumber(Math.abs(balance))}`;

        summaryElement.find('.month-balance').text(balanceText);
        summaryElement.find('.month-expense').text(`支出: ¥${formatMonthNumber(expense)}`);
        summaryElement.find('.month-income').text(`收入: ¥${formatMonthNumber(income)}`);
    }

    // 格式化月份数字显示
    function formatMonthNumber(num) {
        if (num >= 10000) {
            return (num / 10000).toFixed(1) + 'w';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'k';
        }
        return num.toFixed(0);
    }

    // 切换操作菜单显示/隐藏
    window.toggleOptionsMenu = function(transactionId) {
        const menu = document.getElementById(`options-menu-${transactionId}`);
        const allMenus = document.querySelectorAll('.transaction-options-menu');

        // 隐藏其他菜单
        allMenus.forEach(m => {
            if (m.id !== `options-menu-${transactionId}`) {
                m.classList.remove('show');
            }
        });

        // 切换当前菜单
        menu.classList.toggle('show');
    };

    // 点击其他地方隐藏菜单
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.transaction-options').length) {
            $('.transaction-options-menu').removeClass('show');
        }
    });

    // 编辑交易记录
    window.editTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 跳转到编辑页面
        window.location.href = `/transaction/${transactionId}/edit`;
    };

    // 填充编辑表单
    function populateEditForm(transaction) {
        $('#edit-transaction-id').val(transaction.id);
        $('#edit-amount').val(transaction.amount);
        $('#edit-description').val(transaction.description);
        $('#edit-date').val(transaction.transaction_date);

        // 设置交易类型
        $('.type-btn').removeClass('active');
        if (transaction.transaction_type === 1) {
            $('#edit-income-btn').addClass('active');
        } else {
            $('#edit-expense-btn').addClass('active');
        }

        // 加载分类数据
        loadEditCategories(transaction.transaction_type, transaction.category_id, transaction.sub_category_id);
    }

    // 加载编辑表单的分类数据
    function loadEditCategories(transactionType, selectedCategoryId, selectedSubCategoryId) {
        $.ajax({
            url: '/money-categories',
            method: 'GET',
            data: { type: transactionType },
            success: function(response) {
                if (response.success) {
                    renderEditCategories(response.data, selectedCategoryId);
                    if (selectedCategoryId) {
                        loadEditSubCategories(selectedCategoryId, selectedSubCategoryId);
                    }
                }
            }
        });
    }

    // 渲染编辑表单的分类
    function renderEditCategories(categories, selectedId) {
        let html = '';
        categories.forEach(category => {
            const isSelected = category.id === selectedId ? 'active' : '';
            html += `
                <div class="category-item ${isSelected}" data-id="${category.id}">
                    <div class="category-icon">${category.icon}</div>
                    <div class="category-name">${category.name}</div>
                </div>
            `;
        });
        $('#edit-categories').html(html);

        // 绑定点击事件
        $('#edit-categories .category-item').click(function() {
            const categoryId = $(this).data('id');
            $('#edit-categories .category-item').removeClass('active');
            $(this).addClass('active');
            loadEditSubCategories(categoryId);
        });
    }

    // 加载编辑表单的子分类
    function loadEditSubCategories(categoryId, selectedSubCategoryId = null) {
        $.ajax({
            url: '/money-sub-categories',
            method: 'GET',
            data: { category_id: categoryId },
            success: function(response) {
                if (response.success && response.data.length > 0) {
                    renderEditSubCategories(response.data, selectedSubCategoryId);
                    $('#edit-subcategory-group').show();
                } else {
                    $('#edit-subcategory-group').hide();
                }
            }
        });
    }

    // 渲染编辑表单的子分类
    function renderEditSubCategories(subCategories, selectedId) {
        let html = '';
        subCategories.forEach(subCategory => {
            const isSelected = subCategory.id === selectedId ? 'active' : '';
            html += `
                <div class="subcategory-item ${isSelected}" data-id="${subCategory.id}">
                    <div class="subcategory-icon">${subCategory.icon}</div>
                    <div class="subcategory-name">${subCategory.name}</div>
                </div>
            `;
        });
        $('#edit-subcategories').html(html);

        // 绑定点击事件
        $('#edit-subcategories .subcategory-item').click(function() {
            $('#edit-subcategories .subcategory-item').removeClass('active');
            $(this).addClass('active');
        });
    }

    // 切换编辑表单的交易类型
    $('#edit-expense-btn, #edit-income-btn').click(function() {
        const type = $(this).data('type');
        $('.type-btn').removeClass('active');
        $(this).addClass('active');

        // 重新加载分类
        const typeValue = type === 'income' ? 1 : 2;
        loadEditCategories(typeValue);
        $('#edit-subcategories').html('');
        $('#edit-subcategory-group').hide();
    });

    // 保存编辑的交易记录
    $('#edit-save-btn').click(function() {
        const transactionId = $('#edit-transaction-id').val();
        const amount = $('#edit-amount').val();
        const description = $('#edit-description').val();
        const date = $('#edit-date').val();
        const type = $('#edit-income-btn').hasClass('active') ? 1 : 2;
        const categoryId = $('#edit-categories .category-item.active').data('id');
        const subCategoryId = $('#edit-subcategories .subcategory-item.active').data('id');

        // 验证表单
        if (!amount || !date || !categoryId) {
            showError('请填写完整的交易信息');
            return;
        }

        $.ajax({
            url: `/transaction/${transactionId}`,
            method: 'PUT',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {
                amount: amount,
                description: description,
                transaction_date: date,
                transaction_type: type,
                category_id: categoryId,
                sub_category_id: subCategoryId
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('交易记录更新成功');
                    $('#edit-transaction-modal').hide();
                    loadData(); // 重新加载数据
                } else {
                    showError('更新失败：' + response.message);
                }
            },
            error: function(xhr) {
                showError('更新失败，请重试');
            }
        });
    });

    // 删除交易记录
    window.deleteTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 显示删除确认模态框
        $('#delete-transaction-id').val(transactionId);
        $('#delete-transaction-modal').show();
    };

    // 确认删除交易记录
    $('#delete-confirm-btn').click(function() {
        const transactionId = $('#delete-transaction-id').val();

        $.ajax({
            url: `/transaction/${transactionId}`,
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('交易记录删除成功');
                    $('#delete-transaction-modal').hide();
                    loadData(); // 重新加载数据
                } else {
                    showError('删除失败：' + response.message);
                }
            },
            error: function(xhr) {
                showError('删除失败，请重试');
            }
        });
    });

    // 关闭模态框事件
    $('#edit-modal-close, #edit-cancel-btn').click(function() {
        $('#edit-transaction-modal').hide();
    });

    $('#delete-modal-close, #delete-cancel-btn').click(function() {
        $('#delete-transaction-modal').hide();
    });

    // 点击模态框背景关闭
    $('.modal').click(function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    // 渲染交易记录
    function renderTransactions(data) {
        if (data.length === 0) {
            $('#detail-list').html('<div class="no-data"><div class="no-data-icon">📝</div><div class="no-data-text">暂无记录</div><div class="no-data-desc">快去记录你的第一笔账单吧</div></div>');
            return;
        }

        let html = '';
        data.forEach(function(dateGroup) {
            html += `
                <div class="date-group">
                    <div class="detail-date-header" data-date="${dateGroup.date}">
                        <div class="date-info">
                            <div>${dateGroup.formatted_date}</div>
                            <div class="weekday">${dateGroup.weekday}</div>
                        </div>
                        <div class="detail-date-summary">
                            <span>支出: ¥${dateGroup.expense.toFixed(2)}</span>
                            <span>收入: ¥${dateGroup.income.toFixed(2)}</span>
                        </div>
                    </div>
            `;

            dateGroup.transactions.forEach(function(transaction) {
                const amountClass = transaction.type === 'income' ? 'income-amount' : 'expense-amount';
                const amountPrefix = transaction.type === 'income' ? '+' : '-';
                const categoryText = transaction.subcategory_name ?
                    `${transaction.category_name}·${transaction.subcategory_name}` :
                    transaction.category_name;

                // 生成用户头像显示
                let userAvatarHtml = '';
                if (transaction.user_avatar_url) {
                    userAvatarHtml = `<img src="${transaction.user_avatar_url}" alt="${transaction.user_nickname || transaction.user_name}" style="width: 28px; height: 28px; border-radius: 50%; object-fit: cover;">`;
                } else {
                    // 使用昵称首字或用户名首字
                    const displayName = transaction.user_nickname || transaction.user_name;
                    const firstChar = displayName ? displayName.charAt(0).toUpperCase() : 'U';
                    userAvatarHtml = firstChar;
                }
                var note = '';
                if (transaction.note) {
                    note = `<p class="transaction-desc">${transaction.note}</p>`
                }

                html += `
                    <div class="transaction-item" data-id="${transaction.id}">
                        <div class="item-user-avatar">${userAvatarHtml}</div>
                        <div class="transaction-icon">${transaction.category_icon}</div>
                        <div class="transaction-info">
                            <h4>${categoryText}</h4>
                            ${note}
                        </div>
                        <div class="transaction-amount ${amountClass}">${amountPrefix}¥${transaction.amount}</div>
                        <div class="transaction-options">
                            <button class="transaction-options-btn" onclick="toggleOptionsMenu(${transaction.id})">
                                ⋯
                            </button>
                            <div class="transaction-options-menu" id="options-menu-${transaction.id}">
                                <button class="transaction-options-menu-item" onclick="viewTransaction(${transaction.id})">
                                    <i class="fas fa-eye"></i> 查看
                                </button>
                                <button class="transaction-options-menu-item" onclick="editTransaction(${transaction.id})">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="transaction-options-menu-item delete" onclick="deleteTransaction(${transaction.id})">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });

            html += '</div>';
        });

        $('#detail-list').html(html);
    }

    // 查看交易记录
    window.viewTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 跳转到查看页面
        window.location.href = `/transaction/${transactionId}`;
    };

    // 日历功能变量
    let calendarCurrentYear = new Date().getFullYear();
    let calendarCurrentMonth = new Date().getMonth() + 1;
    let calendarData = {};

    // 日历按钮点击事件
    $('#calendar-btn').click(function() {
        $('#calendar-view').css('display', 'flex');
        loadCalendarData();
        generateCalendar();
    });

    // 关闭日历
    $('#calendar-close, .calendar-view').click(function(e) {
        if (e.target === this) {
            $('#calendar-view').hide();
        }
    });

    // 日历导航
    $('#calendar-prev-month').click(function() {
        calendarCurrentMonth--;
        if (calendarCurrentMonth < 1) {
            calendarCurrentMonth = 12;
            calendarCurrentYear--;
        }
        updateCalendarDisplay();
        loadCalendarData();
    });

    $('#calendar-next-month').click(function() {
        calendarCurrentMonth++;
        if (calendarCurrentMonth > 12) {
            calendarCurrentMonth = 1;
            calendarCurrentYear++;
        }
        updateCalendarDisplay();
        loadCalendarData();
    });

    // 更新日历显示
    function updateCalendarDisplay() {
        $('#calendar-month-year').text(`${calendarCurrentYear}年${calendarCurrentMonth}月`);
    }

    // 加载日历数据
    function loadCalendarData() {
        const startDate = `${calendarCurrentYear}-${String(calendarCurrentMonth).padStart(2, '0')}-01`;
        const lastDay = new Date(calendarCurrentYear, calendarCurrentMonth, 0);
        const endDate = `${lastDay.getFullYear()}-${String(lastDay.getMonth() + 1).padStart(2, '0')}-${String(lastDay.getDate()).padStart(2, '0')}`;

        $.ajax({
            url: '{{ route("statistics.trend") }}',
            method: 'GET',
            data: {
                type: 'daily',
                start_date: startDate,
                end_date: endDate
            },
            success: function(response) {
                if (response.success) {
                    calendarData = {};
                    const data = response.data;
                    if (data.labels && data.expense && data.income) {
                        data.labels.forEach(function(label, index) {
                            // 将 MM/DD 格式转换为 YYYY-MM-DD 格式
                            const dateParts = label.split('/');
                            const month = dateParts[0].padStart(2, '0');
                            const day = dateParts[1].padStart(2, '0');

                            // 修复：正确处理年份，特别是跨年的情况
                            let year = calendarCurrentYear;
                            const monthNum = parseInt(month);

                            // 如果当前查看的是1月，但数据中有12月的日期，说明是上一年的数据
                            if (calendarCurrentMonth === 1 && monthNum === 12) {
                                year = calendarCurrentYear - 1;
                            }
                            // 如果当前查看的是12月，但数据中有1月的日期，说明是下一年的数据
                            else if (calendarCurrentMonth === 12 && monthNum === 1) {
                                year = calendarCurrentYear + 1;
                            }

                            const dateStr = `${year}-${month}-${day}`;

                            calendarData[dateStr] = {
                                expense: parseFloat(data.expense[index]) || 0,
                                income: parseFloat(data.income[index]) || 0
                            };
                        });
                    }
                    generateCalendar();
                }
            },
            error: function() {
                console.error('加载日历数据失败');
                generateCalendar();
            }
        });
    }

    // 生成日历
    function generateCalendar() {
        const firstDay = new Date(calendarCurrentYear, calendarCurrentMonth - 1, 1);
        const lastDay = new Date(calendarCurrentYear, calendarCurrentMonth, 0);
        const daysInMonth = lastDay.getDate();
        const startDayOfWeek = firstDay.getDay();
        const today = new Date();

        let html = '';

        // 添加上个月的日期
        const prevMonth = new Date(calendarCurrentYear, calendarCurrentMonth - 2, 0);
        const prevMonthDays = prevMonth.getDate();
        for (let i = startDayOfWeek - 1; i >= 0; i--) {
            const day = prevMonthDays - i;
            // 修复：正确处理跨年的情况
            const prevMonthNum = calendarCurrentMonth - 1;
            const prevYear = prevMonthNum < 1 ? calendarCurrentYear - 1 : calendarCurrentYear;
            const prevMonthFormatted = prevMonthNum < 1 ? 12 : prevMonthNum;
            const prevDateStr = `${prevYear}-${String(prevMonthFormatted).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const prevDayData = calendarData[prevDateStr];

            let prevClasses = 'calendar-day other-month';
            if (prevDayData && (prevDayData.expense > 0 || prevDayData.income > 0)) prevClasses += ' has-data';

            html += `<div class="${prevClasses}" data-date="${prevDateStr}">`;
            html += `<div class="calendar-day-number">${day}</div>`;

            // 为上个月的日期也显示数据
            if (prevDayData) {
                const hasExpense = prevDayData.expense > 0;
                const hasIncome = prevDayData.income > 0;
                const balance = prevDayData.income - prevDayData.expense;

                // 如果同时有支出和收入，显示金色结余
                if (hasExpense && hasIncome) {
                    let balanceText = balance > 0 ? `+${formatNumber(balance)}` : `${formatNumber(balance)}`;
                    html += `<div class="calendar-day-balance">${balanceText}</div>`;

                    // 第二行显示支出和收入
                    html += '<div class="calendar-day-amounts">';
                    html += `<span class="calendar-day-expense">-${formatNumber(prevDayData.expense)}</span>`;
                    html += `<span class="calendar-day-income">+${formatNumber(prevDayData.income)}</span>`;
                    html += '</div>';
                } else {
                    // 只有支出或只有收入，直接显示对应的金额
                    if (hasExpense) {
                        html += `<div class="calendar-day-single calendar-day-expense">-${formatNumber(prevDayData.expense)}</div>`;
                    } else if (hasIncome) {
                        html += `<div class="calendar-day-single calendar-day-income">+${formatNumber(prevDayData.income)}</div>`;
                    }
                }
            }

            html += '</div>';
        }

        // 添加当前月的日期
        for (let day = 1; day <= daysInMonth; day++) {
            const dateStr = `${calendarCurrentYear}-${String(calendarCurrentMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const dayData = calendarData[dateStr];
            const isToday = today.getFullYear() === calendarCurrentYear &&
                           today.getMonth() + 1 === calendarCurrentMonth &&
                           today.getDate() === day;

            let classes = 'calendar-day';
            if (isToday) classes += ' today';
            if (dayData && (dayData.expense > 0 || dayData.income > 0)) classes += ' has-data';

            // 计算结余并设置边框颜色类
            if (dayData) {
                const balance = dayData.income - dayData.expense;
                if (balance > 0) {
                    classes += ' positive-balance';
                } else if (balance < 0) {
                    classes += ' negative-balance';
                }
            }

            html += `<div class="${classes}" data-date="${dateStr}">`;
            html += `<div class="calendar-day-number">${day}</div>`;

            if (dayData) {
                const hasExpense = dayData.expense > 0;
                const hasIncome = dayData.income > 0;
                const balance = dayData.income - dayData.expense;

                // 如果同时有支出和收入，显示金色结余
                if (hasExpense && hasIncome) {
                    let balanceText = balance > 0 ? `+${formatNumber(balance)}` : `${formatNumber(balance)}`;
                    html += `<div class="calendar-day-balance">${balanceText}</div>`;

                    // 第二行显示支出和收入
                    html += '<div class="calendar-day-amounts">';
                    html += `<span class="calendar-day-expense">-${formatNumber(dayData.expense)}</span>`;
                    html += `<span class="calendar-day-income">+${formatNumber(dayData.income)}</span>`;
                    html += '</div>';
                } else {
                    // 只有支出或只有收入，直接显示对应的金额
                    if (hasExpense) {
                        html += `<div class="calendar-day-single calendar-day-expense">-${formatNumber(dayData.expense)}</div>`;
                    } else if (hasIncome) {
                        html += `<div class="calendar-day-single calendar-day-income">+${formatNumber(dayData.income)}</div>`;
                    }
                }
            }

            html += '</div>';
        }

        // 添加下个月的日期
        const totalCells = Math.ceil((startDayOfWeek + daysInMonth) / 7) * 7;
        const remainingCells = totalCells - startDayOfWeek - daysInMonth;
        for (let day = 1; day <= remainingCells; day++) {
            const nextMonth = calendarCurrentMonth + 1 > 12 ? 1 : calendarCurrentMonth + 1;
            const nextYear = calendarCurrentMonth + 1 > 12 ? calendarCurrentYear + 1 : calendarCurrentYear;
            const nextDateStr = `${nextYear}-${String(nextMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const nextDayData = calendarData[nextDateStr];

            let nextClasses = 'calendar-day other-month';
            if (nextDayData && (nextDayData.expense > 0 || nextDayData.income > 0)) nextClasses += ' has-data';

            html += `<div class="${nextClasses}" data-date="${nextDateStr}">`;
            html += `<div class="calendar-day-number">${day}</div>`;

            // 为下个月的日期也显示数据
            if (nextDayData) {
                const hasExpense = nextDayData.expense > 0;
                const hasIncome = nextDayData.income > 0;
                const balance = nextDayData.income - nextDayData.expense;

                // 如果同时有支出和收入，显示金色结余
                if (hasExpense && hasIncome) {
                    let balanceText = balance > 0 ? `+${formatNumber(balance)}` : `${formatNumber(balance)}`;
                    html += `<div class="calendar-day-balance">${balanceText}</div>`;

                    // 第二行显示支出和收入
                    html += '<div class="calendar-day-amounts">';
                    html += `<span class="calendar-day-expense">-${formatNumber(nextDayData.expense)}</span>`;
                    html += `<span class="calendar-day-income">+${formatNumber(nextDayData.income)}</span>`;
                    html += '</div>';
                } else {
                    // 只有支出或只有收入，直接显示对应的金额
                    if (hasExpense) {
                        html += `<div class="calendar-day-single calendar-day-expense">-${formatNumber(nextDayData.expense)}</div>`;
                    } else if (hasIncome) {
                        html += `<div class="calendar-day-single calendar-day-income">+${formatNumber(nextDayData.income)}</div>`;
                    }
                }
            }

            html += '</div>';
        }

        $('#calendar-days').html(html);

        // 绑定日期点击事件
        $('.calendar-day').click(function() {
            const selectedDate = $(this).data('date');
            if (selectedDate) {
                jumpToDate(selectedDate);
            }
        });
    }

    // 跳转到指定日期
    function jumpToDate(dateStr) {
        // 关闭日历
        $('#calendar-view').hide();

        // 直接使用锚点定位到对应日期，不重新加载数据
        const targetElement = $(`.detail-date-header[data-date="${dateStr}"]`);
        if (targetElement.length > 0) {
            $('html, body').animate({
                scrollTop: targetElement.offset().top - 100
            }, 500);
        } else {
            // 如果当前页面没有该日期的数据，则需要重新加载
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;

            // 更新当前年月
            currentYear = year;
            currentMonth = month;

            // 更新显示
            updateCurrentMonthDisplay();

            // 重新加载数据
            loadData();

            // 滚动到指定日期的记录
            setTimeout(function() {
                const targetElement = $(`.detail-date-header[data-date="${dateStr}"]`);
                if (targetElement.length > 0) {
                    $('html, body').animate({
                        scrollTop: targetElement.offset().top - 100
                    }, 500);
                }
            }, 500);
        }
    }

    // 格式化数字
    function formatNumber(num) {
        if (num >= 10000 || num <= -10000) {
            return (num / 10000).toFixed(1) + 'w';
        } else if (num >= 1000 || num <= -1000) {
            return (num / 1000).toFixed(1) + 'k';
        }
        return num.toFixed(1).toString();
    }

    // 更新当前月份显示
    function updateCurrentMonthDisplay() {
        $('#current-month-text').text(currentYear + '年' + currentMonth + '月');
        $('#year-display').text(currentYear);
    }
});
</script>
@endpush
